# -*- coding: utf-8 -*-
"""
Created on Tue Oct 24 09:44:25 2017
修改xml中错误的节点,检查object个数
@author: aia_xml
"""

import xml.etree.ElementTree as ET
import os

'''计算文件夹下文件个数'''
def fileCountIn(dir):
    return sum([len(files) for root,dirs,files in os.walk(dir)])

def change_xml_node(xml_file):
    tree = ET.parse(xml_file)
    root = tree.getroot()
#    for img_name in root.iter('filename'):
#        img_name.text = img_name.text+'.jpg'
        
    
    name_text = 'person'
    obj_num = 0
    chged = 0
    for obj in root.iter('object'):
        if obj.find('name').text == 'object':
            obj.find('name').text = name_text
            chged = 1
        obj_num = obj_num + 1
    if chged == 1:
        print(xml_file,'has been changed')
    if obj_num == 0:
        print(xml_file,'has no object')
    tree.write(xml_file)


def main():
    xml_dir = '/mnt/D/hiksense/dataset/PASCAL_VOC/CUHK_Occlusion/voc/Annotations/'
    xml_Count = fileCountIn(xml_dir)
    print('xml Count in dir:',xml_Count)
    chg_num = 0
    for root,dirs,files in os.walk(xml_dir):
        for file in files:
            xml_file = os.path.join(xml_dir,file)
            change_xml_node(xml_file)
            chg_num = chg_num + 1
            if chg_num%1000 == 0:
                print('completed ',chg_num*100/xml_Count,'% ...')           
    print('completed ',chg_num*100/xml_Count,'% ...')
    print('total:',chg_num)      

if __name__=='__main__':
    main()